package client.shoppingCartFrame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.*;

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;

import client.OCSF.BillSysClient;

import client.shoppingCartFrame.shoppingCart.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShoppingCartPanel extends JPanel implements Observer{

	/**
	 * 
	 */
	private final String VALUTA = " kr ";
	private static final long serialVersionUID = 1L;
	protected ShoppingCart cart;
	protected ObjectList itemList;
	
	protected JTextField totalField;
	private JLabel total = new JLabel("          Total:");
	
	private JButton removeItem = new JButton("Remove Item");
	//private JButton placeOrder = new JButton("Place Order");

	BillSysClient client;
	
	public ShoppingCartPanel(BillSysClient client){
		
		this.client = client;
		
		// Make this class an observer of the shopping cart
	
		cart = new ShoppingCart();
		cart.addObserver(this);

// Create the list of objects in the cart
		itemList = new ObjectList();
		itemList.initTableShoppingCart();

// Create the field for the total cost so far
		totalField = new JTextField(12);
		totalField.setEditable(false);
		Font font = new Font("Verdana", Font.BOLD, 14);
		totalField.setFont(font);
		totalField.setBackground(Color.WHITE);
		totalField.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK));
		totalField.setPreferredSize(new Dimension (160, 50));
		totalField.setHorizontalAlignment(JTextField.RIGHT);
		totalField.setText(cart.total + VALUTA);

		setLayout(new BorderLayout());




	

// Put the name field up at the top and the item list in the center
		/*add("North", namePanel);
		listScrollPane.getViewport().add(itemList);
		listScrollPane.setPreferredSize(new Dimension (300, 200));
		
		tableScrollPane.setPreferredSize(new Dimension (300, 200));*/
		JPanel centerPanel = new JPanel();
		centerPanel.setBackground(Color.WHITE);
		itemList.setLayout(new GridLayout(1,1,2,2));
		itemList.setPreferredSize(new Dimension (360, 340));
		centerPanel.add(itemList);
		
		
		
		setPreferredSize(new Dimension (380,373));
		
		add("Center", centerPanel);
		//add(table);
		
		

// Create buttons for removing items and placing an order and put
// them along the bottom.

		JPanel southPanel = new JPanel();
		southPanel.add(removeItem);
		removeItem.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e){
				try{
					doRemove();
				} catch (Exception ex)
				{
					JOptionPane.showMessageDialog(ShoppingCartPanel.this, ex.getMessage());
					return;
				}
				
			}
			});
		
		/*southPanel.add(placeOrder);
		placeOrder.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e){
				try {
					doPlaceOrder();
				} catch (JAXBException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			});*/
		
		southPanel.setBackground(Color.WHITE);
		//total.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK));
		southPanel.add(total);
		southPanel.add(totalField);

		add("South", southPanel);
		
		setBorder(BorderFactory.createTitledBorder(new EmptyBorder(0,0,13,0), "Shopping cart:"));
		//setBorder(BorderFactory.createTitledBorder());
		
		

// Tell the frame registry about this frame
		PanelRegistry.instance().addPanel("Shopping Cart", this);
		
	}
	
	public String makeItemString(ShoppingCartItem item)
	{
		String itemString = ""+ item.itemName + "" + "     Qty: " + item.quantity + 
				"//t" + "       Cost: " + item.itemCost;
	
		return itemString;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Vector createTableElement(ShoppingCartItem item)
	{
		Vector t = new Vector();
		t.addElement(" " + item.itemName);
		t.addElement(item.quantity);
		t.addElement((item.itemCost.intValue() * item.quantity) + VALUTA);
		//t.addElement(four);
		return t;
	}
	

	public void update(Observable whichCart, Object ob)
	{
		ShoppingCartEvent event = (ShoppingCartEvent) ob;
		

		if (event.eventType == ShoppingCartEvent.ADDED_ITEM) {
// If there is a new item in the cart, add it to the scrollable list
			itemList.addObject(createTableElement(event.item), makeItemString(event.item),
				event.item);					
			totalField.setText(cart.total + VALUTA);
			itemList.validate();
		
		} else if (event.eventType ==
// If an item has been removed from the cart, remove it from the list
			ShoppingCartEvent.REMOVED_ITEM) {
			itemList.delObject(event.item);
					
			totalField.setText(cart.total + VALUTA);
			itemList.validate();
		
		} else if (event.eventType ==
			ShoppingCartEvent.CHANGED_ITEM) {
// If an item has changed, update the list
			int index = itemList.indexOf(event.item);
			itemList.replaceObject(createTableElement(event.item), makeItemString(
				event.item), event.item, index);
			itemList.validate();
			
			totalField.setText(cart.total + VALUTA);
			
		}

	}
	
	// If the user clicks on "Remove Item," remove it from the list
			public void doRemove()
			{
				Object ob = itemList.getSelectedObjectShoppingCart();

				if (ob == null) return;

				ShoppingCartItem item = ((ShoppingCartItem)ob).copy();
				item.quantity = 1;
				cart.removeItem(item);

			}
			
			public boolean isEmpty()
			{
				boolean status;
				ShoppingCartItem [] item = cart.getItems();
				if (item.length == 0){
					status = true;
				}
				else {
					status = false;
				}
				
				return status;
			}
			
			// doPlaceOrder uses PostSockURL to post the order to a web
			// server. You will need to customize this method to fit your needs.

				public ShoppingCartItem [] doPlaceOrder ()
				{
					
				/*	Transaction transaction = new Transaction();
					List <Transaction.Item> itemsList = new ArrayList<Transaction.Item>();
					
					
					transaction.setTransactionNr(orderNr);
					transaction.setSeller(cart.getSellerID());
					transaction.setTotal(cart.total);*/
					
				
				ShoppingCartItem[] items = cart.getItems();
				
				return items;
				
			/*	for (int i=0; i < items.length; i++) 
				{
					Item item = new Item();
					item.setProduct(items[i].itemID);
					item.setQuantity(items[i].quantity);
					item.setReference(orderNr);
					itemsList.add(item);
				}
				transaction.getItem().addAll(itemsList);*/
				
				
			/*	StringWriter writer = new StringWriter();
				JAXBContext context = JAXBContext.newInstance(Transaction.class);
				Marshaller m = context.createMarshaller();
				m.marshal(transaction, writer);
				String test = writer.toString();
			
				try{
					System.out.println(test);
					client.handleMessageFromClientUI(test);
				}catch (Exception x){
					System.out.println("ERROR - doPlaceOrder() - shoppingCartPanel");
				}*/
					
				
				
				//Reset the shopping cart to the next order
			
				}
				
				public void reset()
				{
					cart.resetShoppingCart();
					itemList.deleteAllObjects();
					/*Object ob = itemList.getSelectedObjectShoppingCart();
					
					if (ob == null)*/ return;
				}
				
				public String getTransactionNr()
				{
					String orderNr = cart.generateTransactionNr();
					return orderNr;
				}
				
				public int getSeller()
				{
					int seller = cart.getSellerID();
					return seller;
				}
				
				public int getTotal()
				{
					int total = cart.total;
					return total;
				}

				public ShoppingCart getShoppingCart()
				{
					return cart;
				}
				

}
